package bloodfang.server;

import java.util.EnumSet;
import java.util.HashSet;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import bloodfang.Attacks;
import bloodfang.Cycle;
import bloodfang.CycleCombat2;
import bloodfang.ProcInfo;
import bloodfang.Race;
import bloodfang.RaidBuff;
import bloodfang.SetBonus;
import bloodfang.Settings;
import bloodfang.Stat;
import bloodfang.StatBlock;
import bloodfang.Stats;
import bloodfang.Weapon;
import bloodfang.WeaponType;
 
public class BloodfangProtocol {
 
    public String processInput(String theInput) {
		JSONObject json;
		double dps = 0;
		try {
			json = new JSONObject(theInput);
		
		
			if(!json.has("stats"))
				throw new JSONException("stats field missing");
	    	JSONObject _stats = json.getJSONObject("stats");
	        StatBlock gearStats = new StatBlock();
	        for(Stat stat : Stat.values()){
	        	if(!_stats.has(stat.name())) continue;
	        	gearStats.setStat(stat, _stats.getInt(stat.name()));
	        }
			
	        if(!json.has("race"))
				throw new JSONException("race field missing");
			Race race = Race.valueOf(json.getString("race"));
			
			if(!json.has("mh"))
				throw new JSONException("mh field missing");
			if(!json.has("oh"))
				throw new JSONException("oh field missing");
			JSONObject _mh = json.getJSONObject("mh");
			JSONObject _oh = json.getJSONObject("oh");
			Weapon mh = new Weapon(_mh.getDouble("dps"),_mh.getDouble("speed"),WeaponType.valueOf(_mh.getString("type")));
			Weapon oh = new Weapon(_oh.getDouble("dps"),_oh.getDouble("speed"),WeaponType.valueOf(_oh.getString("type")));
			
			String tal = json.getString("tal");
			
			EnumSet<SetBonus> setB = EnumSet.noneOf(SetBonus.class);
			JSONArray set = json.getJSONArray("set");
			for(int i = 0; i < set.length(); i++){
				setB.add(SetBonus.valueOf(set.getString(i).toUpperCase()));
			}
			
			HashSet<ProcInfo> procs = new HashSet<ProcInfo>();
			JSONArray _procs = json.getJSONArray("procs");
			for(int i = 0; i < _procs.length(); i++){
				JSONObject p = _procs.getJSONObject(i);
				procs.add(new ProcInfo(p.getString("proc"),p.getInt("lvl")));
			}
			
			Settings settings = new Settings();
			
			Stats stats = new Stats(settings, gearStats, race, mh, oh, tal, new HashSet<String>(), EnumSet.allOf(RaidBuff.class), setB, procs);
			Attacks attacks = new Attacks(stats);
			
			Cycle cycle = new CycleCombat2(stats,attacks);
			dps  = cycle.get_dps();
			//cycle.show_dps_breakdown();
			//System.out.println("DPS: " + dps);
			
		} catch (JSONException e) {
			e.printStackTrace();
		}
 
        
        return "{\"dps\":"+dps+"}";
    }
}